<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="close"
  >
    <el-checkbox-group v-model="selRole">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <!-- 这里准备复选框 -->
    <template #footer>
      <el-button type="primary" size="small" @click="addRole">确定</el-button>
      <el-button size="small" @click="$emit('update:showRoleDialog', false)">
        取消
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
// 导入获取用户详情,用于回填
import { getUserDetailById } from '@/api/user'
// 给用户分配角色
import { assignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      selRole: [], // 复选框被选中的值
      roleList: [], // 角色列表
      roleId: '' // 保存当前用户id
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 给员工添加角色
    async addRole () {
      try {
        await assignRoles({ id: this.roleId, roleIds: this.selRole })
        this.$message.success('添加成功')
        this.$emit('update:showRoleDialog', false)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取用户详情回填
    async getRoleDetail (id) {
      const res = await getUserDetailById(id)
      // console.log(res)
      this.selRole = res.roleIds || [] // 后台没有数据会传给一个null, 所以处理一下
      this.roleId = res.id
    },

    // 获取角色列表
    async getRoleList () {
      const data = await getRoleList({ page: 1, pagesize: 100 })
      // console.log(data)
      this.roleList = data.rows
    },
    // 关闭弹层
    close () {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
